package nl.wubinator.aeve.xmlconverters.limited;

import nl.wubinator.aeve.models.limited.skillqueue.QueuedSkill;
import nl.wubinator.aeve.models.limited.skillqueue.SkillQueue;
import nl.wubinator.aeve.xmlconverters.ConverterBase;
import nl.wubinator.aeve.xmlconverters.limited.parsers.QueuedSkillParser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.util.Log;

public class SkillQueueConverter extends ConverterBase {
	// Used to define what elements we are currently in
	private boolean inCurrentTime = false;
	private boolean inCachedUntil = false;
	private boolean inSkillQueue = false;

	// Character object to use for temporary storage
	private QueuedSkill currentQueuedSkill;

	// The complete characters object that will be filled in this converter
	private SkillQueue queue = new SkillQueue();

	public void startElement(String uri, String name, String qName,
			Attributes atts) {
		if (name.trim().equals("currentTime"))
			inCurrentTime = true;
		else if (name.trim().equals("cachedUntil"))
			inCachedUntil = true;
		else if (name.trim().equals("rowset")) {
			String rowsetAttributes = atts.getValue("name");
			if (rowsetAttributes.equals("skillqueue")) {
				inSkillQueue = true;
			}
		} else if (name.trim().equals("row")) {
			if (inSkillQueue)
				this.currentQueuedSkill = QueuedSkillParser.parseAttributes(atts);
		}
	}

	public void endElement(String uri, String name, String qName)
			throws SAXException {
		if (name.trim().equals("currentTime"))
			inCurrentTime = false;
		else if (name.trim().equals("cachedUntil"))
			inCachedUntil = false;
		else if (name.trim().equals("row")) {
			if (inSkillQueue)
				this.queue.addToQueue(this.currentQueuedSkill);
		} else if (name.trim().equals("rowset"))
			inSkillQueue = false;
		else if (name.trim().equals("eveapi"))
			setResult(queue);
	}

	public void characters(char ch[], int start, int length) {
		String chars = (new String(ch).substring(start, start + length));

		try {
			if (chars.equals("\n"))
				return;

			if (inCurrentTime) {
				this.queue.setCurrentTime(chars);
			} else if (inCachedUntil) {
				this.queue.setCachedUntil(chars);
			}
		} catch (Exception e) {
			Log.e("Reading XML error", e.getMessage());
		}
	}
}
